<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'

const list = ref([
  { id: 1, name: '篮球', num: 1 },
  { id: 2, name: '玩具', num: 2 },
  { id: 3, name: '铅笔', num: 5 },
])
const totalNumber = computed(() => {
  return list.value.reduce((sum, item) => sum + item.num, 0)
})
//姓名
const lastName = ref('姓')
const firstName = ref('名')
const name = computed({
  get() {
    return lastName.value + ' ' + firstName.value
  },
  set(value) {
    const arr = value.split(' ')
    lastName.value = arr[0]
    firstName.value = arr[1]
  }
})
//wacth的用法---------------------------
const num = ref(10)
const title = ref('震惊')
watch([num, title], (oldVal, newVal) => {
  console.log('oldVal:', oldVal, '\nnewVal:', newVal)
})
//深度侦听
const obj = reactive({
  name: '小黑',
  age: 18,
  hobby: {
    name: '打篮球',
    level: 10,
  },
})
watch(
  () => obj.hobby.level,
  (newVal, oldVal) => {
    console.log('newVal:', newVal, '\noldVal:', oldVal)
  },
  { deep: true, immediate: true }
)
</script>
<template>
  <div id="app">
    <h3>小黑的礼物清单</h3>
    <table>
      <tr>
        <th>名字</th>
        <th>数量</th>
      </tr>
      <tr v-for="(item) in list" :key="item.id">
        <td>{{ item.name }}</td>
        <td>{{ item.num }}个</td>
      </tr>
    </table>

    <!-- 目标：统计求和，求得礼物总数 -->
    <p>礼物总数：{{ totalNumber }} 个</p>
    <br>
    <hr>
    姓：<input type="text" v-model="lastName">
    <br><br>
    名： <input type="text" v-model="firstName">
    <br><br>
    全名：<input type="text" v-model="name">
  </div>
  <br>
  <hr>
  <br>
  <button @click="num++">点击</button>
  <button @click="title = title + '!'">震惊</button>
  <button @click="obj.hobby.level++">打篮球</button>
</template>

<style>
table {
  border: 1px solid #000;
  text-align: center;
  width: 240px;
}

th,
td {
  border: 1px solid #000;
}

h3 {
  position: relative;
}
</style>
